package com.gylang.crypto.crypto;

import cn.hutool.crypto.CryptoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 加解密上下文对象 存储所有得加解密方法策略
 *
 * @author gylang
 * data 2020/10/28
 * @version v0.0.1
 */
@Component
public class CryptoContext {

	private static final String MESSAGE = "加密异常, 不支持当前解析方式";
	@Autowired
	private Map<String, CryptoStrategy> cryptStrategy;

	/**
	 * 解密
	 *
	 * @param strategy 解密策略
	 * @param key      秘钥/秘钥key
	 * @param content  密文
	 * @return 明文
	 */
	public String decrypt(String strategy, String key, String content) {
		CryptoStrategy cryptoStrategy = cryptStrategy.get(strategy);
		if (null == cryptoStrategy) {
			throw new CryptoException(MESSAGE);
		}
		return cryptoStrategy.decrypt(key, content);
	}

	/**
	 * 加密
	 *
	 * @param strategy 加密策略
	 * @param key      秘钥/秘钥key
	 * @param content  明文
	 * @return 密文
	 */
	public String encrypt(String strategy, String key, String content) {
		CryptoStrategy cryptoStrategy = cryptStrategy.get(strategy);
		if (null == cryptoStrategy) {
			throw new CryptoException(MESSAGE);
		}
		return cryptoStrategy.encrypt(key, content);
	}

	/**
	 * 加签
	 *
	 * @param strategy 验签策略
	 * @param key      秘钥/秘钥key
	 * @param content  待加签内容
	 * @return 签名值
	 */
	public String sign(String strategy, String key, String content) {

		CryptoStrategy cryptoStrategy = cryptStrategy.get(strategy);
		if (null == cryptoStrategy) {
			throw new CryptoException(MESSAGE);
		}
		return cryptoStrategy.sign(key, content);
	}

	/**
	 * 验签
	 *
	 * @param strategy 验签策略
	 * @param key      秘钥/秘钥key
	 * @param content  签名值
	 * @return 验签结果
	 */
	public boolean answer(String strategy, String key, String content) {
		CryptoStrategy cryptoStrategy = cryptStrategy.get(strategy);
		if (null == cryptoStrategy) {
			throw new CryptoException(MESSAGE);
		}
		return cryptoStrategy.answer(key, content);
	}


}
